<?php

/**
 * Description of CollectionBase
 *
 * @author JeyDotC
 */
abstract class CollectionBase implements Countable, IteratorAggregate, ArrayAccess {

    private $valueType;
    protected $collection = array();

    /**
     * Construct a new typed collection
     * @param string valueType collection value type
     */
    public function __construct($valueType) {
        $this->valueType = $valueType;
    }

    /**
     * Return count of items in collection
     * Implements countable
     * @return integer
     */
    public function count() {
        return count($this->collection);
    }

    /**
     * Determine if this value can be added to this collection
     * @param string $value
     * @return boolean
     */
    public function isValidType($value) {
        if($this->valueType == "mixed")
            return true;
        
        $baseType = gettype($value);
        if ($this->valueType == $baseType)
            return true;

        if ($baseType == 'object') {
            $class = get_class($value);

            if ($this->valueType == $class)
                return true;
        }

        return false;
    }
    
    protected function checkType($value) {
        if (!$this->isValidType($value))
            throw new InvalidArgumentException('Trying to add a value of wrong type');
    }


    public function getValueType() {
        return $this->valueType;
    }
    
    /**
     * 
     * @return array
     */
    public function to_array() {
        return $this->collection;
    }

    /**
     * Return an iterator
     * Implements IteratorAggregate
     * @return ArrayIterator
     */
    public function getIterator() {
        return new ArrayIterator($this->collection);
    }
}

?>
